﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using WebApiServer.Models;

namespace WebApiServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        //[HttpPost]
        //public async Task<ActionResult<LoginOutput>> Post(LoginModel model)
        //{
        //    //_context.TodoItems.Add(todoItem);
        //    //await _context.SaveChangesAsync();

        //    ////return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
        //    //return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);

        //    // 
        //    await Task.CompletedTask;
        //    var output = new LoginOutput
        //    {

        //    };
        //    return output;
        //}

        [HttpPost("login")]
        public async Task<ActionResult<object>> Login(LoginModel model)
        {
            //_context.TodoItems.Add(todoItem);
            //await _context.SaveChangesAsync();

            ////return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
            //return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);

            // 
            await Task.CompletedTask;

            if(model.Username == "admin")
            {
                return new
                {
                    data = new 
                    { 
                        id = 500, rid = 0,
                        username = "admin",
                        mobile = "123",
                        email =  "123@qq.com",
                        token = "Bearer " + BuildToken(HttpContext.User)
                    },
                    meta = new
                    {
                        msg = "登录成功",
                        status = 200
                    }
                };
            }

            var output = new 
            { 
                data = "", 
                meta = new 
                { 
                    msg = "登录失败：用户名不存在", 
                    status = 400 
                } 
            };

            return output;
        }

        private string BuildToken(ClaimsPrincipal user)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("jwt中key必须16位以上，否则长度不够会抛出异常")); // _config["Jwt:Key"]
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

            var token = new JwtSecurityToken("Jwt:Issuer", //_config["Jwt:Issuer"]
              "Jwt:Audience",  //_config["Jwt:Issuer"],
              //claims: user.Claims,
              expires: DateTime.Now.AddMinutes(30),
              signingCredentials: creds);

            var handler = new JwtSecurityTokenHandler();
            var jwt = handler.WriteToken(token);
            return jwt;

            //return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}